package worker

import (
	"gitee.com/lyuanbo/stock-plus/internal/svc"
	_ "gitee.com/lyuanbo/stock-plus/internal/worker/message"
	_ "gitee.com/lyuanbo/stock-plus/internal/worker/stock"
	"gitee.com/lyuanbo/stock-plus/pkg/consts"
	storagememory "gitee.com/lyuanbo/stock-plus/pkg/stock/storage_memory"
	"gitee.com/lyuanbo/stock-plus/pkg/stock/types"
	workermanager "gitee.com/lyuanbo/stock-plus/pkg/worker_manager"
	"github.com/alitto/pond/v2"
)

func Run(svcCtx *svc.ServiceContext) {
	workermanager.Run(svcCtx, initCache(svcCtx))
}

func initCache(svcCtx *svc.ServiceContext) *storagememory.Cache {
	cache := storagememory.New(10000)
	var pool = pond.NewPool(20)

	// 获取历史数据
	symbols := svcCtx.Stock.XueQiu.GetSymbols()

	for _, symbol := range symbols {
		for _, period := range svcCtx.Conf.Get().CCI {
			pool.Submit(func() {
				items, _ := svcCtx.Redis.ZRange(svcCtx.Ctx, consts.RedisKeyStockKline(symbol, period), -248, -1).Result()
				if len(items) == 0 {
					return
				}

				key := cache.GetKey(symbol, period)
				rb := cache.GetRingBuffer(key)

				rb.Mux.Lock()
				for _, item := range items {
					var kline types.Kline
					_ = kline.KlineInfo.UnmarshalArray([]byte(item))
					kline.StockInfo = svcCtx.Stock.XueQiu.GetStockInfo(symbol)
					rb.PushBack(&kline)
				}
				rb.Mux.Unlock()
			})
		}
	}
	pool.StopAndWait()
	return cache
}
